package demo1;

import java.util.Arrays;

public class MyArrayList implements List{
    public int[] array;
    public int size;
    public static final int DEFAULT_CAPACITY=5;
    public MyArrayList() {
        array=new int[DEFAULT_CAPACITY];
        size=0;
    }
    public MyArrayList(int initCapacity) {
        array = new int[initCapacity];
        size = 0;
    }

    private void grow(int num){
        array = Arrays.copyOf(array, array.length*num);
    }
    @Override
    public void add(int data) {
        if(isFull()){
            grow(2);
        }
        array[size++]=data;
    }

    @Override
    public void add(int pos, int data) {
        checkPos(pos);
        if(isFull()){
            grow(2);
        }
        for (int i = size-1; i >=pos ; i--) {
            array[i+1]=array[i];
        }
        array[pos]=data;
        size++;
    }

    private void checkPos(int pos){
        if(pos<0||pos>size){
            throw new posOutOfBoundsException("位置不合法");
        }
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < size; i++) {
            if(toFind==array[i]){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < size; i++) {
            if(toFind == array[i]){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        if(isEmpty()){
            throw new EmptyException("顺序表为空.....");
        }
        checkPosByGetOrSet(pos);
        return array[pos];
    }

    private void checkPosByGetOrSet(int pos){
        if(pos<0||pos>=size){
            throw new posOutOfBoundsException("位置不合法");
        }
    }
    @Override
    public void set(int pos, int value) {
        checkPosByGetOrSet(pos);
        array[pos]=value;
    }

    @Override
    public boolean remove(int toRemove) {
        int index = indexOf(toRemove);
        if(index==-1){
            System.out.println("没有找到要删除的元素");
            return false;
        }
        for (int i = index; i < size-1; i++) {
            array[i]=array[i+1];
        }
        size--;
        return true;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void clear() {
        size = 0;
    }

    @Override
    public void display() {
        for (int i = 0; i < size; i++) {
            System.out.print(array[i]+" ");
        }
        System.out.println();
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }
}